/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.bccah.modlib.dbdo.controller
 * @Filename: AcsControlBlockInfoController.java
 * @Description: TODO(AcsControlBlockInfoController)
 * @author: 金鑫智慧
 * @date: 2020-04-03
 * @version: V1.0
 * @Copyright: 2018 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdacsrecord.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.AcsControlBlockInfoDO;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.JurenAcsCommunityInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.TreeCommunity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonConstant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsControlBlockInfoVO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.ResultVO2;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlBlockInfoService;
import com.jinxin.platform.cdacsrecord.core.service.AcsExportService;
import com.jinxin.platform.cdacsrecord.core.service.JurenAcsCommunityService;
import com.jinxin.platform.cdacsrecord.core.service.RestTemplateService;
import com.jinxin.platform.cdacsrecord.core.utils.UploadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;

/**
 * TODO(AcsControlBlockInfoController)
 * @Classn: AcsControlBlockInfoController
 * @author SY
 * @date 2020-04-03
 */
@RestController
@RequestMapping("/basicBlock")
@Slf4j
public class AcsControlBlockInfoController {

    @Autowired
    private AcsControlBlockInfoService blockInfoService;
    @Value("${platform.upload}")
    private String realPath;
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private AcsExportService exportService;
    @Autowired
    private JurenAcsCommunityService communityService;

    /**
     * 获取楼栋信息的分页表
     * @param blockName
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/blockTable")
    public Map getBlockTable(String blockName,int page,int limit,String community){
        Map<String,Object> resultMap = new HashMap<>();
        PageInfo<AcsControlBlockInfoDO> pageInfo = blockInfoService.selParamPage(page,limit,blockName,community);
        resultMap.put("code","0");
        resultMap.put("msg","");
        resultMap.put("count",pageInfo.getTotal());
        resultMap.put("data",pageInfo.getList());
        return resultMap;
    }

    /**
     * 添加楼栋信息
     * @param blockInfoVO
     * @return
     */
    @PostMapping("/addBlock")
    @Transactional
    public ResultEntity addBlockInfo(@Valid AcsControlBlockInfoVO blockInfoVO){
        // save
        AcsControlBlockInfoDO infoDO = new AcsControlBlockInfoDO();
        BeanUtils.copyProperties(blockInfoVO,infoDO );
        infoDO.setCreateTime(LocalDateTime.now());
        infoDO.setState("0");
        try{
            ResultVO2 resultVO = restTemplateService.buildingblockOperate(Constant.OPERATION_SIGN_ADD, infoDO);
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                infoDO.setBlockId(resultVO.getObject().toString());
                blockInfoService.saveDO(infoDO);
                log.info(infoDO.toString());
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
            }
            String desc = resultVO != null ? resultVO.getRstDesc() : "添加失败，请稍后重试";
            return new ResultEntity(CommonCodeEntity.FAIL, desc,"" );
        }
        catch (Exception e){
            log.error("addBlockInfo:",e );
            return new ResultEntity(CommonCodeEntity.FAIL, "添加失败，请稍后重试","" );
        }
    }

    /**
     * 删除楼栋信息
     * @param bid
     * @return
     */
    @PostMapping("/delBlock")
    @Transactional
    public ResultEntity delBlock(String bid,String companyId,String code){
        if(StringUtils.isEmpty(bid) || StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.FAIL,"id为空，删除失败","" );
        }
        if(StringUtils.isEmpty(code)){
            return new ResultEntity(CommonCodeEntity.FAIL,"小区编号为空，删除失败","" );
        }
        AcsControlBlockInfoDO infoDO = new AcsControlBlockInfoDO();
        infoDO.setBlockId(bid);
        infoDO.setCompanyId(companyId);
        infoDO.setHousingEstateId(code);
        ResultVO2 resultVO = restTemplateService.buildingblockOperate(Constant.OPERATION_SIGN_DEL, infoDO);
        if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
            if(blockInfoService.delDO(bid) == 1){
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
            }else{
                return new ResultEntity(CommonCodeEntity.FAIL,"删除失败，请稍后重试","" );
            }
        }else {
            String desc = resultVO != null ? resultVO.getRstDesc() : "删除失败，请稍后重试";
            return new ResultEntity(CommonCodeEntity.FAIL, desc,"" );
        }
    }

    /**
     * 更新楼栋信息
     * @param blockInfoVO
     * @return
     */
    @PostMapping("/upBlock")
    @Transactional
    public ResultEntity upBlock(@Valid AcsControlBlockInfoVO blockInfoVO){
        if(StringUtils.isEmpty(blockInfoVO.getBlockId() )){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"ID为空","" );
        }
        AcsControlBlockInfoDO infoDO = new AcsControlBlockInfoDO();
        BeanUtils.copyProperties(blockInfoVO, infoDO);
        log.info(infoDO.toString());
//        try{
//            blockInfoService.updateDO(infoDO);
//            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
//        }catch (Exception e){
//            log.error("upBlock:",e );
//            return new ResultEntity(CommonCodeEntity.FAIL,"更新失败，请稍后重试","" );
//        }
        try{
            ResultVO2 resultVO = restTemplateService.buildingblockOperate(Constant.OPERATION_SIGN_EDIT, infoDO);
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                infoDO.setBlockId(resultVO.getObject().toString());
                blockInfoService.updateDO(infoDO);
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
            }
            String desc = resultVO != null ? resultVO.getRstDesc() : "更新失败，请稍后重试";
            return new ResultEntity(CommonCodeEntity.FAIL, desc,"" );
        }
        catch (Exception e){
            log.error("updateBlockInfo:",e );
            return new ResultEntity(CommonCodeEntity.FAIL, "更新失败，请稍后重试","" );
        }
    }

    /**
     * 获取楼栋记录
     * @return
     */
    @PostMapping("/selBlockList")
    public ResultEntity selBlockList(String name,String community){
        AcsControlBlockInfoDO blockInfoDO = new AcsControlBlockInfoDO();
        if(!StringUtils.isEmpty(name)){
            blockInfoDO.setBlockName(name);
        }
        if(!StringUtils.isEmpty(community)){
            blockInfoDO.setCompanyId(community);
        }
        List<AcsControlBlockInfoDO> resList = blockInfoService.selDOByInfo(blockInfoDO);
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",resList);
    }

    /**
     * 导入楼栋信息
     * @param file
     * @return
     */
    @PostMapping("/uploadBlock")
    public ResultEntity uploadBlock(MultipartFile file,String community,String housingEstateId) {
        if(StringUtils.isEmpty(community)){
            return new ResultEntity(CommonCodeEntity.FAIL,"小区未选择","" );
        }
        try {
            Map<String,String> resMap = blockInfoService.uploadBlock(file, community,housingEstateId);
            return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
        } catch (Exception e) {
            log.error("error",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"导入失败，请修改后重试","" );
        }
    }

    @RequestMapping("/exportBlock2Excel")
    public void exportBlock2Excel(HttpServletResponse response, String communityId){
        exportService.exportBlock2Excel(response, communityId);
    }

    /**
     * 下载模板资源
     * @param response
     */
    @RequestMapping("/downTemplate")
    public void downProdFile(  HttpServletResponse response,String type ){
        String filename = "";
        if(type.equals(CommonConstant.TEMP_BLOCK) ){
            filename = CommonConstant.TEMP_BLOCK_NAME;
        }
        if(type.equals(CommonConstant.TEMP_ROOM) ){
            filename = CommonConstant.TEMP_ROOM_NAME;
        }
        if(type.equals(CommonConstant.TEMP_USER) ){
            filename = CommonConstant.TEMP_USER_NAME;
        }
        UploadFileUtil.downFile(realPath,filename,response );
    }

    @RequestMapping("/syncData")
    public ResultEntity syncData(String companyId){
        Map<String,Object> resultMap = new HashMap<>();
        ResultEntity resultEntity = restTemplateService.listBuildingAreaTree(companyId);
        if(resultEntity != null){
            if(!"000".equals(resultEntity.getResultCode())){
                resultEntity.setResultDesc(resultEntity.getResultDesc());
                return resultEntity;
            }
            JSONArray dataResult = (JSONArray)resultEntity.getResultContent();
            List<TreeCommunity> communityList = new ArrayList<>(); // 小区列表
            Map<String,List<TreeCommunity>> buildingMap = new LinkedHashMap<>();
            List<String> idList = new ArrayList<>();
            for (int i = 0; i < dataResult.size(); i++) { // 应该只有一个
                JSONObject jsonObject = dataResult.getJSONObject(i);
                TreeCommunity info = JSON.parseObject(JSON.toJSONString(jsonObject), TreeCommunity.class);
                if(info != null){
                    // 小区表中的插入code (这里的id)
                    JurenAcsCommunityInfo communityInfo = communityService.selectByKey(companyId);
                    if(communityInfo != null && StringUtils.isEmpty(communityInfo.getCode())){
                        communityInfo.setCode(info.getId()+"");
                        communityService.updateByKey(communityInfo);
                    }
                    communityList.add(info);
                    JSONObject jo = info.getAdditionalParameters();
                    List<TreeCommunity> childrenList = JSON.parseArray(jo.get("children").toString(), TreeCommunity.class);
                    if(i == 0){
                        AcsControlBlockInfoDO blockInfoDO = new AcsControlBlockInfoDO();
                        blockInfoDO.setCompanyId(companyId);
                        List<AcsControlBlockInfoDO> list = blockInfoService.selDOByInfo(blockInfoDO);
                        for(AcsControlBlockInfoDO blockInfo : list){
                            idList.add(blockInfo.getBlockId());
                        }
                    }
                    for (TreeCommunity blockInfo: childrenList){
                        String blockId = blockInfo.getId() + "";
                        AcsControlBlockInfoDO blockInfo2 = blockInfoService.getById(blockId);
                        if(blockInfo2 == null){
                            blockInfo2 = new AcsControlBlockInfoDO();
                            blockInfo2.setCompanyId(companyId);
                            blockInfo2.setBlockId(blockId);
                            blockInfo2.setBlockName(blockInfo.getText()+"");
                            blockInfo2.setBlockDesc(blockInfo.getText()+"");
                            blockInfoService.saveDO(blockInfo2);
                        }else {
                            idList.remove(blockId);
                        }
                    }
                    buildingMap.put(info.getId()+"", childrenList);
                }
            }
            // 删除不存在数据
            for (String id : idList) {
                blockInfoService.delDO(id);
            }
            resultMap.put("communityList", communityList);
            resultMap.put("buildingMap", buildingMap);
        }
        return resultEntity;
    }

}
